import 'package:date_format/date_format.dart';
import 'package:get/get.dart';
import 'package:mziot/app/config/constant.dart';
import 'package:mziot/app/modules/auth/mine_provider.dart';
import 'package:mziot/app/tools/global_const.dart';
import 'package:mziot/app/tools/tools.dart';

class AuthProfileController extends GetxController {
  MineProvider provider = MineProvider();

  final language = 999.obs;
  final timeZone = ''.obs;
  final time = ''.obs;
  final email = ''.obs;

  @override
  void onInit() {
    super.onInit();

    fetchMineInfo();
    language.value = GlobalConst.sharedPreferences?.getInt(Constant.kLanguage) ?? 999;
    final zone = GlobalConst.userModel?.userTimeZone;
    if(zone != null) {
      final index = Constant.codeList.indexWhere((element) => element == int.parse(zone));
      updateTimeZone(index);
    }
  }

  void updateTimeZone(int index) {
    timeZone.value = Constant.timeZones[index].zone;
    var timeStr = Constant.timeZones[index].time.replaceAll('GMT+', '');
    timeStr = timeStr.replaceAll('GMT', '');
    logger.v('timeStr $timeStr');
    final times = timeStr.split(':');
    final hour = int.parse(times.first);
    final minutes = int.parse(times.last);
    final now = DateTime.now().toUtc();
    final date = now.add(Duration(hours: hour, minutes: minutes));
    time.value = formatDate(date, [yyyy, '-', mm, '-', dd, ' ', HH, ':', nn, ':', ss]);
  }

  void fetchMineInfo() {
    provider.takeMineInfo().then((value) {
      if (value.isSuccess) {
        email.value = value.data?.userName ?? '';
        final zone = value.data?.timezone ?? '0';
        final code = int.parse(zone);
        final index = Constant.codeList.indexWhere((element) => element == code);
        updateTimeZone(index);
      }
    });
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {}
}
